<?php
/**
 * Auth
 *
 * @Description 描述
 * @Author look
 * @CreateTime 2022/2/23
 */

namespace app\common\Attributes;

use app\common\exception\ApiException;
use app\common\utils\AuthMenu;
use app\common\utils\AuthToken;
use app\common\utils\ErrorCode;
use think\Request;

/**
 *
 */
#[\Attribute(\Attribute::TARGET_METHOD)]
class Auth {

    /**
     * @param string $path 权限标识
     */
    public function __construct(private string $perm) {}

    public function exec(Request $request) {
        // 权限认证
        $authorization = $request->header('authorization');
        if (!$authorization || !str_starts_with($authorization, "Bearer ")) {
            throw new ApiException(...ErrorCode::TOKEN_ERROR);
        }
        $token = substr($authorization, 7);
        // 解析token 获取用户信息
        $jwt_data = (new AuthToken())->analysisToken($token);

        // 验证资源访问权限
        (new AuthMenu($jwt_data['admin_id'], $this->perm))->checkAuth();
    }

}